// pages/productDetails/productDetails
let app = getApp();
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		status: app.globalData.statusHeight, //头部占位高度
		navHeight: app.globalData.navHeight, //头部内容区
		interval: 3000, //自动切换时间间隔
		duration: 500, //轮播图滑动动画时长
		numOfSliders: 1, //滑块数
		upgTheShopkeeper:
			'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/mine/UCPTlF.png', //升级掌柜图
		productParameters: [], //产品参数数据
		paramPopup: false, // sku弹窗
		productParamPopup: false, //参数弹窗
		shareItonClose: false, //分享弹窗
		active: [0],
		collect: false, //收藏
		type: 0, //0是普通,1是拼团
		typeTwo: 0, //0是普通,1是拼团
		stepper: 1, //选择数量
		video_id: '', //视频id
		homeOrBack: 0, // 0返回首页，1返回上一页
		timeData: {},
		lives: '', //是否从直播商品跳过来

		invitation_code:'', // 拼团简介
		optionsBtnType: 0, //0是普通,1是拼团

		collectCouponsLayer: false, // 是否显示领取优惠卷弹窗
		couponList:[], // 优惠卷列表

		commodity:{},

		isClickShoppingCart: false, // 是否点击加入购物车
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		let that = this;
		console.log('options--11111---',options);
		this.setData({
			typeTwo:options.typeTwo
		})
		wx.loadFontFace({
			family: 'numFont',
			source:
				'url("https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/6e57ceb9c0c4e41b1b54b99194242b6e.ttf")',
		});
		if (options.uid) {
			that.setData({
				shareIt: 1,
			});
		}
		//是否从直播商品跳过来的
		if (options.lives) {
			that.setData({
				lives: 'lives',
			});
		}
		that.setData({
			productId: options.id ? options.id : 290,
			video_id: options.activityId ? options.activityId : '',
			type: options.type ? options.type : '',
			videoid: options.video_id ? options.video_id : '',
			shareIt: app.store.$state.shareIt ? app.store.$state.shareIt : 0,
		});
		app.store.setState({
			uid: options.uid ? options.uid : app.store.$state.uid,
			invite_code: options.code
				? options.code
				: app.store.$state.invite_code,
		});
		// 解析
		if (options.scene) {
			let scene = decodeURIComponent(options.scene);
			var arrPara = scene.split('&');
			var arr = [];
			for (var i in arrPara) {
				arr = arrPara[i].split('=');
				if (i == 0) {
					app.store.setState({
						invite_code: arr[1],
					});
				} else if (i == 1) {
					app.store.setState({
						uid: arr[1] ? arr[1] : '',
					});
					that.setData({
						uid: arr[1] ? arr[1] : '',
					});
				} else {
					that.setData({
						productId: arr[1] ? arr[1] : '',
					});
					app.store.setState({
						id: arr[1] ? arr[1] : '',
					});
				}
			}
		}
		if (options.uid || that.data.uid) {
			that.setData({
				shareIt: 1,
			});
		}
		//判断onLaunch是否执行完毕
		if (app.globalData.checkLogin) {
			that.reqIntfc();
		} else {
			app.checkLoginReadyCallback = (res) => {
				that.reqIntfc();
			};
		}
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		this.topReturnBtn(); // 判断顶部返回按钮
	},

	// 请求接口
	reqIntfc() {
		let that = this;
		that.get_mall_getMalls();
		// that.get_mall_commentgetMalls();  // 商城-商品评论列表
		if (app.store.$state.invite_code) {
			that.bindInvitationCd();
			that.setData({
				shareIt: 1,
			});
		}
	},

	// 关闭立即领劵弹层
	closeCollectCoupons() {
		this.setData({
			collectCouponsLayer: !this.data.collectCouponsLayer,
		});
	},

	// 拼团简介
	getTipsDetails(){
		let that = this;
		app.http({
			url: app.api.ruleSpecifications,
			data: {
				key: 'activity_describe',
			},
			//method: 'get',
		})
			.then((res) => {
				// console.log('res-----222--',res.data.data.val);
				that.setData({
					invitation_code: res.data.data.val,
				});
			})
			.catch((err) => {});
	},
	// 获取商品详情
	get_mall_getMalls() {
		let that = this;
		app.http({
			url: app.api.get_mall_getMalls,
			data: {
				id: that.data.productId,
				lives: that.data.lives ? that.data.lives : '',
			},
			//method: 'get',
		})
			.then((res) => {
				let requsetData = res.data.data;
				console.log("requestData---", requsetData);

				// 组合选中状态数据
				var linshi = [];
				var pin_str = [];
				var obj = res.data.data.attrOjb;
				for (let i = 0; i < obj.length; i++) {
					obj[i].actives = [];
					obj[i].strs = [];
					for (let z = 0; z < obj[i].vals.length; z++) {
						obj[i].actives[z] = z == 0 ? 1 : 0;
						obj[i].strs[z] = obj[i].key + '_' + obj[i].vals[z];
					}
				}
				//that.setData({ active: linshi });
				let b = res.data.data.attrs;

				// 组合规格数组价格 数据
				for (let index = 0; index < b.length; index++) {
					if (b[index].valjson) {
						var linshi = [];
						for (const key in b[index].valjson) {
							linshi.push(key + '_' + b[index].valjson[key]);
						}
						b[index].valjson = linshi;
					}
				}
				let a = obj;
				let valsNum = [];
				for (let i = 0; i < a.length; i++) {
					for (let t = 0; t < a[i].vals.length; t++) {
						valsNum.push(a[i].vals[t]);
					}
				}
				let desc = res.data.data.commodity.desc;
				desc = desc.replace(
					/<img/gi,
					'<img style="max-width:100%;height:auto;display:block" '
				);
				that.setData({
					commodity: res.data.data.commodity,
					attrs: res.data.data.attrs,
					attrsData: res.data.data.attrs[0],
					attrOjb: res.data.data.attrOjb,
					type: res.data.data.commodity.is_activity,
					valsNum: valsNum.slice(0, 4),
					desc: desc,
				});

				if (res.data.data.commodity.coupon_true){
					that.getCouponList({
						id: requsetData.commodity.id
					})
				}

				setTimeout(()=>{
					that.get_mall_commentgetMalls();  // 商城-商品评论列表
					that.getTipsDetails(); //  获取说明
				},100)

			})
			.catch((err) => {});
	},

	// 获取优惠卷列表
	getCouponList(param){
		let that = this;
		app.http({
			url: app.api.mallIndexCoupon,
			data: {
				id: param.id, // 商品id
			},
		})
			.then((res) => {
				let requestData = res.data.data;
				requestData.map(mapRes =>{
					mapRes.start_time = app.util.timestampToTime(mapRes.start_time);
					mapRes.end_time = app.util.timestampToTime(mapRes.end_time);
				})
				that.setData({
					couponList: requestData
				})
				console.log('获取优惠卷列表---requestData---',requestData);
			})
			.catch((err) => {});
	},

	// 优惠卷弹层---确定按钮
	couponLayerBtn(){
		this.setData({
			collectCouponsLayer: !this.data.collectCouponsLayer
		})
	},

	// 领取优惠卷
	receiveCoupon(ev){
		let that = this;
		let item = ev.currentTarget.dataset.item;
		let index = ev.currentTarget.dataset.index;
		let couponList = this.data.couponList;
		if (couponList[index].apply_status == 1){ // 点击已领取的优惠卷
			console.log('点击已领取的优惠卷---')
			return ;
		}
		// console.log("领取优惠卷---item",item);
		// console.log("领取优惠卷---index",index);
		// console.log("领取优惠卷---couponList",couponList);

		app.http({
			url: app.api.userCouponApplyCoupon,
			data: {
				coupon_id: item.id, // 优惠卷id
			},
		})
			.then((res) => {
				// console.log('领取优惠卷---res---',res.data.code);
				if (res.data.code == 200){
					wx.showToast({
						title: '领取成功',
						icon: 'success',
						duration: 1500
					})
					couponList[index].apply_status = 1;
					that.setData({
						couponList
					})
				}
			})
			.catch((err) => {});
	},

	// 获取商品评论
	get_mall_commentgetMalls() {
		let that = this;
		app.http({
			url: app.api.get_mall_commentgetMalls,
			data: {
				goods_id: that.data.productId,
				limit: 2,
				page: 1,
			},
			//method: 'get',
		})
			.then((res) => {
				that.setData({
					commentgetMalls: res.data.data.data,
					totComments: res.data.data.total,
				});
			})
			.catch((err) => {});
	},
	// 滑块监听
	sliderMonitoring(e) {
		let that = this;
		that.setData({
			numOfSliders: e.detail.current + 1,
		});
	},
	// 产品规格参数弹窗
	onClose(e) {
		let that = this;
		if (e.currentTarget.dataset.type == 'shoppingCart') {
			that.setData({
				isClickShoppingCart: !that.data.isClickShoppingCart,
			});
		} else {
			// setTimeout(() => {
			// 	that.setData({
			// 		gwc: 0,
			// 	});
			// }, 500);
		}

		that.setData({
			paramPopup: !that.data.paramPopup,
		});
		// if (e.currentTarget.dataset.i == 'gwc') {
		// 	that.setData({
		// 		paramPopup: !that.data.paramPopup,
		// 		gwc: 1,
		// 	});
		// } else {
		// 	that.setData({
		// 		paramPopup: !that.data.paramPopup,
		// 	});
		// 	setTimeout(() => {
		// 		that.setData({
		// 			gwc: 0,
		// 		});
		// 	}, 500);
		// }
	},
	// 分享好友弹窗
	shareItonClose() {
		let that = this;
		that.setData({
			shareItonClose: !that.data.shareItonClose,
		});
	},
	// 选择产品
	chooseProduct(e) {
		let that = this;
		let data = e.currentTarget.dataset;
		let a = that.data.attrOjb;
		let b = that.data.attrs;
		// 等于1  表示选中 否则 没有选中
		let value = a[data.key].actives[data.ind] == 1 ? 0 : 1;
		// 当前组 是否有选中的
		if (a[data.key] && a[data.key].actives.indexOf(1) >= 0) {
			// 清除选中的
			for (let index = 0; index < a[data.key].actives.length; index++) {
				a[data.key].actives[index] = 0;
			}
		}
		a[data.key].actives[data.ind] = value;
		that.getClickAttrDataMoney(a, b);
		that.setData({
			attrOjb: a,
		});
	},
	// 根据所选数据进行显示对应的规格组价格
	getClickAttrDataMoney(data, attrsData) {
		let that = this;
		var clicks = [];
		for (let index = 0; index < data.length; index++) {
			for (let z = 0; z < data[index].vals.length; z++) {
				// 判断是否选中,添加已经拼接字符串
				if (data[index].actives[z] == 1) {
					clicks.push(data[index].strs[z]);
				}
			}
		}
		// 相当于用户目前所选的规格
		// 每次 将  所有规格数组信息(价格-规格参数) 进行遍历 匹配 用户当前所选的规格
		for (let index = 0; index < attrsData.length; index++) {
			// 判断是否相等
			if (attrsData[index].valjson.join(',') == clicks.join(',')) {
				// 进行渲染
				that.setData({ attrsData: attrsData[index] });
				break;
			}
		}
	},
	// 选择数量
	onChange(event) {
		let that = this;
		that.setData({
			stepper: event.detail,
		});
	},
	// 产品规格参数弹窗
	prodOnClose() {
		let that = this;
		that.setData({
			productParamPopup: !that.data.productParamPopup,
		});
	},
	// 客服中心
	handleContact(e) {},
	// 是否收藏
	collect() {
		let that = this;
		if (!that.data.commodity.is_collect) {
			app.http({
				url: app.api.post_index_addCollect,
				data: {
					gid: that.data.commodity.id,
				},
			})
				.then((res) => {
					that.setData({
						collect: !that.data.collect,
					});
				})
				.catch((err) => {});
		} else {
			app.http({
				url: app.api.post_index_delCollect,
				data: {
					gid: that.data.commodity.id,
				},
			})
				.then((res) => {
					that.setData({
						collect: !that.data.collect,
					});
				})
				.catch((err) => {});
		}
		that.get_mall_getMalls(that.data.productId);
	},
	// 预览图片
	previewPic(e) {
		if (e.currentTarget.dataset.img) {
			wx.previewImage({
				current: e.currentTarget.dataset.img, // 当前显示图片的http链接
				urls: [e.currentTarget.dataset.img],
			});
		} else {
			wx.previewImage({
				current: e.currentTarget.dataset.i, // 当前显示图片的http链接
				urls: e.currentTarget.dataset.item, // 需要预览的图片http链接列表
			});
		}
	},
	// 跳到全部评论
	allComments() {
		let that = this;
		let productId = that.data.productId;
		wx.navigateTo({
			url: `/pages/allComments/allComments?id=${productId}`,
		});
	},
	// 升级掌柜
	upgTheShopkeeper() {
		let that = this;
		let productId = that.data.productId;
		wx.navigateTo({
			url: `/pages/ownershipRights/ownershipRights?id=${productId}`,
		});
	},
	// 待删除
	gwcTest(){
		wx.showToast({
			title: '暂未开通',
			icon: 'none',
			duration: 1500
		})
		return ;
	},
	// 添加到购物车
	gwc(e) {
		// wx.showToast({
		// 	title: '暂未开通',
		// 	icon: 'none',
		// 	duration: 1500
		// })
		// return ;
		console.log('添加到购物车');
		let that = this;
		let type = e.currentTarget.dataset.type;
		if (type == 0) {
			wx.switchTab({
				url: '/pages/shoppingCart/shoppingCart',
			});
		} else {
			console.log(that.data.attrsData);
		}
	},
	// 购买
	buyBtn() {
		let that = this;

		let b = that.data.stepper;
		let c = that.data.commodity;
		let d = null;

		// stepper
		let attrsData = this.data.attrsData;
		attrsData.selectNumber = this.data.stepper;
		attrsData.name = c.name;
		let goodsArray = JSON.stringify([attrsData]);

		let video_id = that.data.video_id;
		let videoid = that.data.videoid;

		if (this.data.isClickShoppingCart){
			this.addShoppingCart(); // 添加购物车
		} else {
			if (c.is_activity == 1) {
				d = null;
			} else {
				d = c.default_discount_price_share;
			}
			let productId = that.data.productId;
			wx.navigateTo({
				url: `/pages/order/paymentOrder/paymentOrder?id=${productId}&goodsArray=${goodsArray}&stepper=${b}&name=${c.name}&price_share=${d}&videoid=${videoid}&activ=${video_id}&lives=${that.data.lives}`,
			});
		}
	},

	// 添加购物车
	addShoppingCart(){
		let that = this;
		let commodity = this.data.commodity; // 商品详情数据
		let stepper = this.data.stepper; // 数量
		let skuId = this.data.attrsData.id;
		// console.log("commodity---", commodity);
		// console.log("stepper---", stepper);
		// console.log("skuId---", skuId);
		// return ;
		app.http({
			url: app.api.shoppingIndexFavorites,
			data: {
				goods_id: commodity.id, // 商品id
				goods_attr_id: skuId, // 商品规格记录
				num: stepper, // 数量
			},
			//method: 'get',
		})
			.then((res) => {
				let requestData = res.data;
				// console.log("requestData---", requestData);
				if (requestData.code == 200){
					wx.showToast({
						title: '添加成功',
						icon: 'success',
						duration: 1500
					})
					that.setData({
						paramPopup: !that.data.paramPopup,
					});
				}
			})
			.catch((err) => {

			});
	},


	//跳到合成海报页面
	generatePoster() {
		let that = this;
		let id = that.data.productId;
		wx.navigateTo({
			url: `/pages/syntheticPoster/syntheticPoster?id=${id}&type=1&page=pages/productDetails/productDetails`,
		});
	},
	//品牌介绍
	brandIntroduction() {
		let that = this;
		let id = that.data.commodity.bid;
		wx.navigateTo({
			url: `/pages/brandIntroduction/brandIntroduction?id=${id}`,
		});
	},
	// 微信授权
	GetUserInfo(e) {
		let that = this;
		//用户按了允许授权按钮
		if (e.detail.userInfo) {
			app.http({
				url: app.api.post_my_updateUserInfo,
				data: {
					encryptedData: e.detail.encryptedData,
					iv: e.detail.iv,
					rawData: e.detail.rawData,
					signature: e.detail.signature,
				},
			})
				.then((res) => {})
				.catch((err) => {});
			getApp().store.setState({
				login: true,
				getPhoneNumber: true,
				// infoData: e.detail.userInfo,
			});
			wx.setStorageSync('login', true);
		} else {
			wx.showToast({
				title: '您取消了授权',
				icon: 'none',
				duration: 1500,
			});
		}
	},
	// 手机号
	PhoneNumber(e) {
		let that = this;
		// 登录
		wx.login({
			success(res) {
				let header = {};
				if (res.code) {
					app.http({
						url: '/user/login/wxLogin',
						data: {
							code: res.code,
						},
						header: header,
					})
						.then((res) => {
							wx.setStorageSync('token', res.data.data.token);
							if (e.detail.iv) {
								app.http({
									url: app.api.post_index_bindingPhone,
									data: {
										encryptedData: e.detail.encryptedData,
										iv: e.detail.iv,
									},
								}).then((res) => {
									getApp().store.setState({
										login: true,
										getPhoneNumber: false,
										loginType: 2,
									});
								});
							} else {
								wx.showToast({
									title: '您取消了授权',
									icon: 'none',
									duration: 1500,
								});
							}
						})
						.catch((err) => {});
				}
			},
			fail: (err) => {},
		});
	},
	getPhone() {
		app.store.setState({
			getPhoneNumber: true,
		});
	},
	/**
	 * 生命周期函数--监听页面卸载
	 */ onUnload: function () {
		app.store.setState({
			shareIt: 0,
		});
	},
	// 倒计时
	onChange1(e) {
		this.setData({
			timeData: e.detail,
		});
	},

	// 复制商品名称
	copyTitle() {
		let that = this;
		wx.setClipboardData({
			data: that.data.commodity.title,
			success(res) {
				wx.getClipboardData({
					success(res) {},
				});
			},
		});
	},

	// 顶部返回按钮
	topReturnBtn() {
		let pages = getCurrentPages(); //获取所有页面
		console.log('pages---',pages);
		console.log('pages.length---',pages.length);
		if (pages.length <= 1){
			// 返回首页
			this.setData({
				homeOrBack: 0
			})
		} else {
			// 返回上一页
			this.setData({
				homeOrBack: 1
			})
		}
	},

	// 返回上一页
	back() {
		if (this.data.homeOrBack == 0) {
			wx.switchTab({
				url: '/pages/tabBar/index/index',
			});
		} else {
			wx.navigateBack({
				delta: 1,
			});
		}
	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function (res) {
		let that = this;
		let invite_code = app.store.getState().infoData.invite_code;
		let uid = app.store.getState().infoData.id;
		let id = that.data.productId;
		let bg = that.data.commodity.share;
		if (res.from === 'button') {
			return {
				title: that.data.commodity.title,
				path: `/pages/productDetails/productDetails?code=${invite_code}&uid=${uid}&id=${id}`,
				imageUrl: bg,
				success() {},
				fail() {},
				complete() {},
			};
		}
		return;
	},

// 	/*
// * 分享到朋友圈
// * */
// 	onShareTimeline: function (res) {
// 		let that = this;
// 		let invite_code = app.store.getState().infoData.invite_code;
// 		let uid = app.store.getState().infoData.id;
// 		let id = that.data.productId;
// 		let bg = that.data.commodity.share;
// 		if (res.from === 'button') {
// 			return {
// 				title: that.data.commodity.title,
// 				path: `/pages/productDetails/productDetails?code=${invite_code}&uid=${uid}&id=${id}`,
// 				// query: `code=${invite_code}&uid=${uid}&id=${id}`,
// 				query: `id=293`,
// 				imageUrl: bg,
// 				success() {},
// 				fail() {},
// 				complete() {},
// 			};
// 		}
// 		return;
// 	},
});
